﻿using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 通用控制器
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.03.06
    /// </summary>
    [Route("api/Common")]
    public class UtilsController : BaseApiController
    {
        #region 上传文件/图片
        /// <summary>
        /// 上传文件/图片
        /// </summary>
        /// <returns></returns>
        [HttpPost("Uploader/{type}")]
        [AllowAnonymous]
        public ResponseResult Uploader(string type)
        {
            Thread.Sleep(1000);
            var file = Utils.HttpContext.Current.Request.Form.Files[0];
            var fileType = Path.GetExtension(file.FileName).Replace(".", "");
            if (!this.AllowFileType(fileType, type))
            {
                return Error("上传失败，文件格式不允许上传");
            }
            var _filePath = GetPathByType(type);
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + CommonHelper.Guid.ToString() + Path.GetExtension(file.FileName);
            using (var stream = new FileStream(_filePath + _fileName, FileMode.Create))
            {
                file.CopyTo(stream);
            }
            var response = new
            {
                name = _fileName,
                url = string.Format("/api/Common/Image/{0}/{1}", type, _fileName)
            };
            return Success("上传成功", response);
        }
        #endregion

        #region 上传图片
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost("UploadImage")]
        public ResponseResult UploadImage()
        {
            var file = Utils.HttpContext.Current.Request.Form.Files[0];
            var ImgType = Path.GetExtension(file.FileName).Replace(".", "");
            if (!this.AllowImageType(ImgType))
            {
                return Error("上传失败，图片格式不允许上传");
            }
            var filePath = ConfigurationKey.TemporaryFilePath;
            var fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + CommonHelper.Guid.ToString() + Path.GetExtension(file.FileName);
            using (var stream = new FileStream(filePath + fileName, FileMode.Create))
            {
                file.CopyTo(stream);
            }
            return Success("上传成功", fileName);
        }
        #endregion

        #region 下载附件
        /// <summary>
        /// （后端使用）下载文件链接
        /// </summary>
        /// <param name="fileModel">文件对象</param>
        /// <param name="fileName">文件名</param>
        [HttpPost("Download/{fileName}")]
        [AllowAnonymous]
        public string Download([FromBody] FileModel fileModel, string fileName)
        {
            var temporaryFilePath = ConfigurationKey.TemporaryFilePath + fileModel.FileId;
            var systemFilePath = ConfigurationKey.SystemFilePath + fileModel.FileId;
            if (FileHelper.Exists(temporaryFilePath))
                FileHelper.DownloadFile(temporaryFilePath, fileName);
            else
                FileHelper.DownloadFile(systemFilePath, fileName);
            return systemFilePath + "/" + fileName;
        }

        /// <summary>
        /// 获取下载文件链接
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet("Download/{type}/{fileName}")]
        [AllowAnonymous]
        public ResponseResult DownloadUrl(string type, string fileName)
        {
            var userInfo = UserProvider.Instance.Get();
            return Success(new { name = fileName, url = "/api/Common/Download?encryption=" + userInfo.Id + "|" + fileName + "|" + type });
        }

        /// <summary>
        /// 下载文件链接
        /// </summary>
        [HttpGet("Download")]
        [AllowAnonymous]
        public void DownloadFile()
        {
            var reqjson = Utils.HttpContext.Current.Request.Query["encryption"];
            if (reqjson.IsNotEmptyOrNull())
            {
                var data = reqjson.ToString().Split("|");
                var token = data.Length > 0 ? data[0] : "";
                if (CacheFactory.Cache.Exists(token))
                {
                    var fileName = data.Length > 1 ? data[1] : "";
                    string type = data.Length > 2 ? data[2] : "";
                    var filePath = GetPathByType(type) + fileName;
                    if (FileHelper.Exists(filePath))
                    {
                        FileHelper.DownloadFile(filePath, fileName);
                    }
                    else
                    {
                        FileHelper.DownloadFile(ConfigurationKey.SystemFilePath, fileName);
                    }
                }
            }
        }
        #endregion

        #region 获取图片
        /// <summary>
        /// （后端使用）生成图片链接
        /// </summary>
        /// <param name="type">图片类型 </param>
        /// <param name="fileName">注意 后缀名前端故意把 .替换@ </param>
        /// <returns></returns>
        [HttpGet("Image/{type}/{fileName}")]
        [AllowAnonymous]
        public FileContentResult GetImg(string type, string fileName)
        {
            var imgPath = GetPathByType(type) + fileName.Replace("@", ".");
            var imgByte = FileHelper.ReadAllBytes(imgPath);
            var imgStream = new MemoryStream();
            if (imgByte.IsNotEmptyOrNull())
            {
                imgStream = new MemoryStream(imgByte);
            }
            return File(imgStream.ToArray(), @"image/jpg");
        }
        #endregion

        #region 验证码
        /// <summary>
        /// 获取图形验证码
        /// </summary>
        /// <param name="timestamp">时间戳</param>
        /// <returns></returns>
        [HttpGet("ImageCode/{timestamp}")]
        [AllowAnonymous]
        public FileContentResult GetCode(string timestamp)
        {
            var verifyCode = new VerifyCodeHelper().GetVerifyCode();
            var stream = (MemoryStream)verifyCode["stream"];
            var code = verifyCode["code"].ToString();
            if (!string.IsNullOrEmpty(code))
                CacheFactory.Cache.Insert("timestamp", timestamp);
            CacheFactory.Cache.Insert(CacheKey.VALIDCODE + timestamp, code);
            return File(stream.ToArray(), @"image/png");
        }
        #endregion

        #region 获取IM聊天图片+语音
        /// <summary>
        /// 获取IM聊天图片
        /// </summary>
        /// <param name="fileName">注意 后缀名前端故意把 .替换@ </param>
        /// <returns></returns>
        [HttpGet("IMImage/{fileName}")]
        [AllowAnonymous]
        public FileContentResult GetIMImage(string fileName)
        {
            var imgPath = ConfigurationKey.IMContentFilePath + fileName.Replace("@", ".");
            var imgByte = FileHelper.ReadAllBytes(imgPath);
            var imgStream = new MemoryStream(imgByte);
            return File(imgStream.ToArray(), @"image/jpg");
        }
        /// <summary>
        /// 获取IM聊天语音
        /// </summary>
        /// <param name="fileName">注意 后缀名前端故意把 .替换@ </param>
        /// <returns></returns>
        [HttpGet("IMVoice/{fileName}")]
        [AllowAnonymous]
        public FileContentResult GetIMVoice(string fileName)
        {
            var imgPath = ConfigurationKey.IMContentFilePath + fileName.Replace("@", ".");
            var imgByte = FileHelper.ReadAllBytes(imgPath);
            var imgStream = new MemoryStream(imgByte);
            return File(imgStream.ToArray(), @"audio/mp3");
        }
        #endregion

        #region 移动APP应用接口
        /// <summary>
        /// App启动获取信息
        /// </summary>
        /// <param name="appName">app应用名称</param>
        /// <returns></returns>
        [HttpGet("AppStartInfo/{appName}")]
        [AllowAnonymous]
        public ResponseResult GetAppStartInfo(string appName)
        {
            var data = new
            {
                AppVersion = ConfigurationKey.AppVersion,
                AppUpdataContent = ConfigurationKey.AppUpdataContent,
            };
            return Success(data);
        }
        #endregion

        #region Method
        /// <summary>
        /// 允许文件类型
        /// </summary>
        /// <param name="fileExtension">文件后缀名</param>
        /// <returns></returns>
        private bool AllowFileType(string fileExtension, string type)
        {
            var isOk = false;
            var allowExtension = ConfigurationKey.AllowUploadFileType;
            if (type.Equals("weixin"))
            {
                allowExtension = ConfigurationKey.WeChatUploadFileType;
            }
            foreach (var item in allowExtension)
            {
                if (item == fileExtension.ToLower())
                {
                    isOk = true;
                    break;
                }
                else
                {
                    isOk = false;
                }
            }
            return isOk;
        }
        /// <summary>
        /// 允许文件类型
        /// </summary>
        /// <param name="fileExtension">文件后缀名</param>
        /// <returns></returns>
        private bool AllowImageType(string fileExtension)
        {
            var isOk = false;
            var allowExtension = ConfigurationKey.AllowUploadImageType;
            foreach (var item in allowExtension)
            {
                if (item == fileExtension.ToLower())
                {
                    isOk = true;
                    break;
                }
                else
                {
                    isOk = false;
                }
            }
            return isOk;
        }

        /// <summary>
        /// 根据类型获取文件存储路径
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private string GetPathByType(string type)
        {
            switch (type)
            {
                case "userAvatar":
                    return ConfigurationKey.UserAvatarFilePath;
                case "mail":
                    return ConfigurationKey.EmailFilePath;
                case "IM":
                    return ConfigurationKey.IMContentFilePath;
                case "weixin":
                    return ConfigurationKey.MPMaterialFilePath;
                case "workFlow":
                    return ConfigurationKey.SystemFilePath;
                case "annex":
                    return ConfigurationKey.SystemFilePath;
                case "annexpic":
                    return ConfigurationKey.SystemFilePath;
                case "document":
                    return ConfigurationKey.DocumentFilePath;
                case "dataBackup":
                    return ConfigurationKey.DataBackupFilePath;
                case "preview":
                    return ConfigurationKey.DocumentPreviewFilePath;
                case "codeGenerator":
                    return ConfigurationKey.CodeGeneratorFilePath;
                default:
                    return ConfigurationKey.TemporaryFilePath;
            }
        }
        #endregion
    }
}
